package org.cerberus.platform.client;

import java.util.List;

public final class ClientComponent {

	private Integer objectID;
	private Object[] data;
	private ClientClass clazz;

	public ClientComponent(ClientClass clazz) {
		if (clazz == null) {
			throw new NullPointerException();
		}
		this.clazz = clazz;
		this.data = new Object[clazz.getAttributeCount()];
	}
	
	ClientComponent(ClientClass clazz, Object[] data) {
		this.clazz = clazz;
		this.data = data;
	}
	
	public String getClassID() {
		return clazz.getClassID();
	}
	
	public ClientClass getClientClass() {
		return clazz;
	}
	
	public Attribute getAttribute(String attributeName) {
		return new Attribute(this, getAttributeIndex(attributeName));
	}
	
	public Object get(String attributeName) {
		int index = getAttributeIndex(attributeName);
		if (index == -1) {
			throw new ClientClassException("Invalid attribute "+clazz.getClassID()+"."+attributeName);
		}
		return data[index];
	}
	
	public void set(String attributeName, Object value) {
		int index = getAttributeIndex(attributeName);
		if (index == -1) {
			throw new ClientClassException("Invalid attribute "+clazz.getClassID()+"."+attributeName);
		}
		if ((data[index] == null && value != null) 
				|| (data[index] == null && value == null) 
				|| !data[index].equals(value)) {
			data[index] = value;
			getPeer().attributeChanged(this, index);
		}
	}
	
	public ClientComponent copy() {
		Object[] copied = new Object[data.length];
		System.arraycopy(data, 0, copied, 0, data.length);
		return new ClientComponent(clazz, copied);
	}
	
	public void flush() {
		getPeer().flushComponent(this);
	}
	
	IClientPeer getPeer() {
		return clazz.getPeer();
	}
	
	public int getAttributeIndex(String attributeName) {
		return clazz.getAttributeIndex(attributeName);
	}
	
	public int getAttributeCount() {
		return clazz.getAttributeCount();
	}
	
}
